<?php
# Name: Database.class.php
# File Description: MySQL Class to allow easy and clean access to common mysql commands
# Author: ricocheting
# Web: http://www.ricocheting.com/scripts/
# Update: 2/2/2009
# Version: 2.1
# Copyright 2003 ricocheting.com


/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/



//require("config.php");
//$db = new Database($config['server'],$config['user'],$config['pass'],$config['database'],$config['tablePrefix']);


###################################################################################################
###################################################################################################
###################################################################################################

class Database {

private $server   = ""; //database server
private $user     = ""; //database login name
private $pass     = ""; //database login password
private $database = ""; //database name
private $pre      = ""; //table prefix


#######################
//internal info
private $record = array();

private $error = "";
private $errno = 0;

//table name affected by SQL query
private $fieldTable= "";

//number of rows affected by SQL query
private $affectedRows = 0;

private $linkId = 0;
private $queryId = 0;


#-#############################################
# desc: constructor
public function __construct($server, $user, $pass, $database, $pre=''){
	$this->server=$server;
	$this->user=$user;
	$this->pass=$pass;
	$this->database=$database;
	$this->pre=$pre;
}#-#constructor()


#-#############################################
# desc: connect and select database using vars above
# Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters
function connect($new_link=false) {
	$this->linkId=@mysql_connect($this->server,$this->user,$this->pass,$new_link);

	if (!$this->linkId) {//open failed
		$this->oops("Could not connect to server: <b>$this->server</b>.");
		}

	if(!@mysql_select_db($this->database, $this->linkId)) {//no database
		$this->oops("Could not open database: <b>$this->database</b>.");
		}

	// unset the data so it can't be dumped
	$this->server='';
	$this->user='';
	$this->pass='';
	$this->database='';
}#-#connect()


#-#############################################
# desc: close the connection
function close() {
	if(!mysql_close($this->linkId)){
		$this->oops("Connection close failed.");
	}
}#-#close()


#-#############################################
# Desc: escapes characters to be mysql ready
# Param: string
# returns: string
function escape($string) {
	if(get_magic_quotes_gpc()) $string = stripslashes($string);
	return mysql_real_escape_string($string);
}#-#escape()


#-#############################################
# Desc: executes SQL query to an open connection
# Param: (MySQL query) to execute
# returns: (queryId) for fetching results etc
function query($sql) {
	// do query
	$this->queryId = @mysql_query($sql, $this->linkId);

	if (!$this->queryId) {
		$this->oops("<b>MySQL Query fail:</b> $sql");
	}
	
	$this->affectedRows = @mysql_affected_rows();

	return $this->queryId;
}#-#query()


#-#############################################
# desc: fetches and returns results one line at a time
# param: queryId for mysql run. if none specified, last used
# return: (array) fetched record(s)
function fetchRow($queryId=-1) {
	// retrieve row
	if ($queryId!=-1) {
		$this->queryId=$queryId;
	}

	if (isset($this->queryId)) {
		$this->record = @mysql_fetch_assoc($this->queryId);
	}else{
		$this->oops("Invalid queryId: <b>$this->queryId</b>. Records could not be fetched.");
	}

	// unescape records
	if($this->record){
		$this->record=array_map("stripslashes", $this->record);
		//foreach($this->record as $key=>$val) {
		//	$this->record[$key]=stripslashes($val);
		//}
	}
	return $this->record;
}#-#fetchRow()


#-#############################################
# desc: returns all the results (not one row)
# param: (MySQL query) the query to run on server
# returns: assoc array of ALL fetched results
function fetchAllArray($sql) {
	$queryId = $this->query($sql);
	$out = array();

	while ($row = $this->fetchRow($queryId, $sql)){
		$out[] = $row;
	}

	$this->freeResult($queryId);
	return $out;
}#-#fetchAllArray()


#-#############################################
# desc: frees the resultset
# param: queryId for mysql run. if none specified, last used
function freeResult($queryId=-1) {
	if ($queryId!=-1) {
		$this->queryId=$queryId;
	}
	if(!@mysql_freeResult($this->queryId)) {
		$this->oops("Result ID: <b>$this->queryId</b> could not be freed.");
	}
}#-#freeResult()


#-#############################################
# desc: does a query, fetches the first row only, frees resultset
# param: (MySQL query) the query to run on server
# returns: array of fetched results
function queryFirst($query_string) {
	$queryId = $this->query($query_string);
	$out = $this->fetchRow($queryId);
	$this->freeResult($queryId);
	return $out;
}#-#queryFirst()


#-#############################################
# desc: does an update query with an array
# param: table (no prefix), assoc array with data (doesn't need escaped), where condition
# returns: (queryId) for fetching results etc
function update($table, $data, $where='1') {
	$q="UPDATE `".$this->pre.$table."` SET ";

	foreach($data as $key=>$val) {
		if(strtolower($val)=='null') $q.= "`$key` = NULL, ";
		elseif(strtolower($val)=='now()') $q.= "`$key` = NOW(), ";
		else $q.= "`$key`='".$this->escape($val)."', ";
	}

	$q = rtrim($q, ', ') . ' WHERE '.$where.';';

	return $this->query($q);
}#-#update()


#-#############################################
# desc: does an insert query with an array
# param: table (no prefix), assoc array with data
# returns: id of inserted record, false if error
function insert($table, $data) {
	$q="INSERT INTO `".$this->pre.$table."` ";
	$v=''; $n='';

	foreach($data as $key=>$val) {
		$n.="`$key`, ";
		if(strtolower($val)=='null') $v.="NULL, ";
		elseif(strtolower($val)=='now()') $v.="NOW(), ";
		else $v.= "'".$this->escape($val)."', ";
	}

	$q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";

	if($this->query($q)){
		//$this->freeResult();
		return mysql_insert_id();
	}
	else return false;

}#-#insert()


#-#############################################
# desc: build an insert query with an array
# param: table (no prefix), assoc array with data
# returns: id of inserted record, false if error
function buildInsert($table, $data) {
	$q="INSERT INTO `".$this->pre.$table."` ";
	$v=''; $n='';

	foreach($data as $key=>$val) {
		$n.="`$key`, ";
		if(strtolower($val)=='null') $v.="NULL, ";
		elseif(strtolower($val)=='now()') $v.="NOW(), ";
		else $v.= "'".$this->escape($val)."', ";
	}

	$q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .") ";
	
	return $q;
}#-#insert()


#-#############################################
# desc: throw an error message
# param: [optional] any custom error to display
function oops($msg='') {
	if($this->linkId>0){
		$this->error=mysql_error($this->linkId);
		$this->errno=mysql_errno($this->linkId);
	}
	else{
		$this->error=mysql_error();
		$this->errno=mysql_errno();
	}
	?>
		<table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;">
		<tr><th colspan=2>Database Error</th></tr>
		<tr><td align="right" valign="top">Message:</td><td><?php echo $msg; ?></td></tr>
		<?php if(strlen($this->error)>0) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?>
		<tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \t g:i:s A"); ?></td></tr>
		<tr><td align="right">Script:</td><td><a href="<?php echo @$_SERVER['REQUEST_URI']; ?>"><?php echo @$_SERVER['REQUEST_URI']; ?></a></td></tr>
		<?php if(strlen(@$_SERVER['HTTP_REFERER'])>0) echo '<tr><td align="right">Referer:</td><td><a href="'.@$_SERVER['HTTP_REFERER'].'">'.@$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?>
		</table>
	<?php
}#-#oops()



public function getAffectedNumRows(){
    return $this->affectedRows;
}

}//CLASS Database
###################################################################################################

?>